<template>
  <div class="app-container">
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="上传资源用户" prop="userId">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入上传资源用户"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="资源名" prop="name">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入资源名"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分类" prop="category">
              <el-select v-model="queryParams.category" placeholder="请选择分类" clearable style="width: 100%">
                <el-option
                  v-for="dict in resource_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="存储方式" prop="storageType">
              <el-select v-model="queryParams.storageType" placeholder="请选择存储方式" clearable style="width: 100%">
                <el-option
                  v-for="dict in resource_storage_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option
                  v-for="dict in resource_state"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="search-buttons">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-row :gutter="10" class="mb8 toolbar-row">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['resource:resource:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['resource:resource:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['resource:resource:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['resource:resource:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table 
        v-loading="loading" 
        :data="resourceList" 
        @selection-change="handleSelectionChange"
        class="resource-table"
        border
        stripe
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="上传资源用户" align="center" prop="userName" />
        <el-table-column label="资源名" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="分类" align="center" prop="category" width="120">
          <template #default="scope">
            <dict-tag :options="resource_category" :value="scope.row.category"/>
          </template>
        </el-table-column>
        <el-table-column label="下载量" align="center" prop="downloads" width="100" />
        <el-table-column label="存储方式" align="center" prop="storageType" width="120">
          <template #default="scope">
            <dict-tag :options="resource_storage_type" :value="scope.row.storageType"/>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <dict-tag :options="resource_state" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <!-- 本地服务器存储地址列 -->
        <!-- <el-table-column label="本地服务器存储地址" align="center" prop="servePath" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.storageType === 1">{{ scope.row.servePath }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              icon="Edit" 
              @click="handleUpdate(scope.row)" 
              v-hasPermi="['resource:resource:edit']"
              size="small"
            >修改</el-button>
            <el-button 
              link 
              type="danger" 
              icon="Delete" 
              @click="handleDelete(scope.row)" 
              v-hasPermi="['resource:resource:remove']"
              size="small"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        class="pagination-container"
      />
    </el-card>

    <!-- 添加或修改资源对话框 -->
    <el-dialog  v-model="open" width="600px" append-to-body>
      <div class="dialog-header">
        <h3 class="dialog-title">{{ title }}</h3>
      </div>
      <el-form ref="resourceRef" :model="form" :rules="rules" label-width="120px" class="resource-form">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="资源名" prop="name">
              <el-input v-model="form.name" placeholder="请输入资源名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="dict in resource_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="存储方式" prop="storageType">
              <el-select v-model="form.storageType" placeholder="请选择存储方式" style="width: 100%" @change="handleStorageTypeChange">
                <el-option
                  v-for="dict in resource_storage_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <!-- 网盘存储字段 -->
          <el-col :span="24" v-if="form.storageType === 0">
            <el-form-item label="网盘地址" prop="panPath">
              <el-input v-model="form.panPath" placeholder="请输入网盘地址" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.storageType === 0">
            <el-form-item label="网盘验证码" prop="panCode">
              <el-input v-model="form.panCode" placeholder="请输入网盘验证码" />
            </el-form-item>
          </el-col>
          
          <!-- 本地服务器存储字段 -->
          <el-col :span="24" v-if="form.storageType === 1">
            <el-form-item label="本地服务器存储" prop="servePath">
              <file-upload v-model="form.servePath" :limit="1" :file-size="100" :file-type="[]" button-text="上传文件" />
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in resource_state"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Resource">
import { listResource, getResource, delResource, addResource, updateResource } from "@/api/resource/resource"
import FileUpload from "@/components/FileUpload/index.vue"

const { proxy } = getCurrentInstance()
const { resource_storage_type, resource_state, resource_category } = proxy.useDict('resource_storage_type', 'resource_state', 'resource_category')

const resourceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    name: null,
    category: null,
    storageType: null,
    status: null,
    userName: null
  },
  rules: {
    name: [
      { required: true, message: "资源名不能为空", trigger: "blur" }
    ],
    category: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    storageType: [
      { required: true, message: "存储方式不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询资源列表 */
function getList() {
  loading.value = true
  listResource(queryParams.value).then(response => {
    resourceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    name: null,
    category: null,
    downloads: null,
    isFree: null,
    payType: null,
    storageType: null,
    panPath: null,
    panCode: null,
    servePath: null,
    status: null,
    createTime: null,
    userName : null
  }
  proxy.resetForm("resourceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 手动重置 userName 字段
  queryParams.value.userName = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加资源"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getResource(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改资源"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["resourceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateResource(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addResource(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  const resourceNames = row.name || resourceList.value.filter(item => ids.value.includes(item.id)).map(item => item.name).join(', ')
  proxy.$modal.confirm('是否确认删除资源"' + resourceNames + '"').then(function() {
    return delResource(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('resource/resource/export', {
    ...queryParams.value
  }, `resource_${new Date().getTime()}.xlsx`)
}

/** 存储方式改变时的处理 */
function handleStorageTypeChange(value) {
  // 清空之前存储方式的字段值
  if (value === 0) {
    form.value.servePath = null
  } else if (value === 1) {
    form.value.panPath = null
    form.value.panCode = null
  }
}

getList()
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #f5f7f9;
  min-height: 100%;
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  padding: 20px 0;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.toolbar-row {
  margin-bottom: 20px;
}

.resource-table {
  margin-bottom: 20px;
}

.resource-table :deep(.el-table__header th) {
  background-color: #f8f9fa;
  color: #606266;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.resource-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 0 20px 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e4e7ed;
  background-color: #f8f9fa;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  color: #2d3a4f;
  margin: 0;
}

</style>